package com.a01_2021.thousandstimes.instance.controller;


import com.a01_2021.thousandstimes.exception.CustomException;
import com.a01_2021.thousandstimes.general.jwt.JwtTokenUtil;
import com.a01_2021.thousandstimes.instance.entity.LearnToday;
import com.a01_2021.thousandstimes.instance.service.ILearnTodayService;
import com.a01_2021.thousandstimes.utils.AjaxResponse;
import com.baomidou.dynamic.datasource.annotation.DS;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author E1xP
 * @since 2021-03-28
 */
@RestController
@RequestMapping("/learnToday")
public class LearnTodayController {

    @Resource
    JwtTokenUtil jwtTokenUtil;

    @Resource
    ILearnTodayService learnTodayService;

    /**
     * 用于添加今日学记录
     *
     * @param token   jwt令牌
     * @param content 今日学内容
     * @return AjaxResponse
     */
    @PreAuthorize("hasAuthority('learnToday-add')")
    @DS("#header.instanceid")
    @PostMapping("add")
    public AjaxResponse add(@RequestHeader("${jwt.header}") String token, String content) {
        long userId = Long.parseLong(jwtTokenUtil.getUserIdFromToken(token));
        LearnToday learnToday = learnTodayService.add(userId, content);
        return AjaxResponse.success(learnToday);
    }

    /**
     * 用于获取过去今日学记录
     *
     * @param token jwt令牌
     * @return AjaxResponse
     */
    @PreAuthorize("hasAuthority('learnToday-get')")
    @DS("#header.instanceid")
    @PostMapping("get")
    public AjaxResponse get(@RequestHeader("${jwt.header}") String token) {
        long userId = Long.parseLong(jwtTokenUtil.getUserIdFromToken(token));
        List<LearnToday> learnTodayList = learnTodayService.get(userId);
        return AjaxResponse.success(learnTodayList);
    }

    /**
     * 用于更新今日学记录
     *
     * @param token      jwt令牌
     * @param learnToday 今日学更新实体
     * @return AjaxResponse
     * @throws CustomException 当今日学不存在，该今日学不属于该用户是抛出该异常
     */
    @PreAuthorize("hasAuthority('learnToday-update')")
    @DS("#header.instanceid")
    @PostMapping("update")
    public AjaxResponse update(@RequestHeader("${jwt.header}") String token, LearnToday learnToday) throws CustomException {
        long userId = Long.parseLong(jwtTokenUtil.getUserIdFromToken(token));
        LearnToday result = learnTodayService.update(userId, learnToday);
        return AjaxResponse.success(result);
    }
}
